using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using GonzalesCore.CoreElements;
using GonzalesCore.CoreManagers;
using Kypris2.CoreElements;
using Kypris2.Utils;
using Jamila2.Tools;

using iTextSharp.text;
using iTextSharp.text.pdf;


public partial class GonzalesLogChangeAuthorizer : System.Web.UI.Page
{

    #region Variables
    protected PrivateLoginSession CurrentPrivateSession = null;
    protected LogManager CurLogManager = null;
    protected DataView ResultView = null;
    
    #region ResultTable
    protected DataTable ResultTable
    {
        get { return (DataTable)ViewState["ResultTable"]; }
        set { ViewState["ResultTable"] = value; }
    }
    #endregion

    #region UnexpectedError
    protected string UnexpectedError
    {
        get
        {
            return ViewState["UnexpectedError"].ToString();
        }

        set
        {
            ViewState["UnexpectedError"] = value;
        }
    }
    #endregion

    #region Download
    protected string Download
    {
        get
        {
            return ViewState["Download"].ToString();
        }

        set
        {
            ViewState["Download"] = value;
        }
    }
    #endregion

    #region DateRangeMessage
    protected string DateRangeMessage
    {
        get
        {
            return ViewState["DateRangeMessage"].ToString();
        }

        set
        {
            ViewState["DateRangeMessage"] = value;
        }
    }
    #endregion

    #region ProperDateMessage
    protected string ProperDateMessage
    {
        get
        {
            return ViewState["ProperDateMessage"].ToString();
        }

        set
        {
            ViewState["ProperDateMessage"] = value;
        }
    }
    #endregion

    #region GridViewHeader
    protected ArrayList GridViewHeader
    {
        get
        {
            return (ArrayList)ViewState["GridViewHeader"];
        }

        set
        {
            ViewState["GridViewHeader"] = value;
        }
    }
    #endregion

    #endregion

    #region Events

    protected void Page_Load(object sender, EventArgs e)
    {
        this.SessionCheck();

        this.Table_MessageBox.Visible = false;  // always default to false
        this.HyperLink_FileDownload.Visible = false;

        if (!IsPostBack)
        {
            this.PageComponentSetup();
            this.SwitchLanguage();
        }
    }

    protected void Button_Submit_Click(object sender, EventArgs e)
    {
        this.LoadData(true);
    }

    #region LoadData(bool)
    private bool LoadData(bool ab_Binding)
    {
        bool valid = true;
        StringBuilder ErrorMessageBuilder = new StringBuilder("<ul>");

        #region Date Validation

        if (this.TextBox_SubmittedDateFrom.Text.Length == 0 || this.TextBox_SubmittedDateTo.Text.Length == 0)
        {
            ErrorMessageBuilder.AppendLine("<li>" + this.DateRangeMessage + "</li>");
            valid = false;
        }
        else
        {
            try
            {
                // try to convert to date
                DateTime Date1 = SwissArmy.DateConvert(this.TextBox_SubmittedDateFrom.Text, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedDateFormat);
                DateTime Date2 = SwissArmy.DateConvert(this.TextBox_SubmittedDateTo.Text, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedDateFormat);

                if (Date1 == DateTime.MinValue || Date2 == DateTime.MinValue)
                {
                    ErrorMessageBuilder.AppendLine("<li>" + this.ProperDateMessage + "</li>");
                    valid = false;
                }
            }
            catch (Exception)
            {
                ErrorMessageBuilder.AppendLine("<li>" + this.ProperDateMessage + "</li>");
                valid = false;
            }

        }
        ErrorMessageBuilder.AppendLine("</ul>");

        #endregion

        if (valid)
        {
            this.LoadData();
            if (this.ResultTable != null && ab_Binding)
            {
                this.BindData(this.ResultView);
            }
            return true;
        }
        else
        {
            this.ShowErrorMessage(ErrorMessageBuilder.ToString());
            return false;
        }    
    }
    #endregion

    protected void Button_CSV_Click(object sender, EventArgs e)
    {
        //this.Button_Submit_Click(sender, e);
        if (!this.LoadData(false)) return;

        if (this.ResultTable != null)
        {
            //string FileName = "ChangeLog-Authorizer-" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + ".csv";
            string ErrorMessage = string.Empty;

            // remove unnecessary column
            DataTable ResultTableForOutput = this.ResultView.ToTable();
            if (!pdf(ResultTableForOutput))
            {
                string LogID = SwissArmy.UniqueID();
                this.CurLogManager.LogError(LogID, "[GonzalesLogChangeAuthorizer.Button_CSV_Click] : Failed at PDFGenerator.ExportPDFFile : " + ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                this.ShowErrorMessage(this.UnexpectedError + LogID);
            }
            //else
            //{
            //    this.HyperLink_FileDownload.Text = this.Download + PDFGenerator.pdfFileName;
            //    this.HyperLink_FileDownload.NavigateUrl = "ReportsOutput/" + PDFGenerator.pdfFileName;
            //    this.HyperLink_FileDownload.Visible = true;
            //}
        } 
    }

    private bool pdf(DataTable dataTable)
    {
        // Build pdf file name
        string pdfFileName = "LogChange-" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + ".pdf";

        Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 20);
        pdfDoc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
        System.IO.MemoryStream mStream = new System.IO.MemoryStream();
        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, mStream);

        int cols = dataTable.Columns.Count;
        int rows = dataTable.Rows.Count;
        pdfDoc.Open();

        PdfPTable pdfTable = new PdfPTable(cols);
        pdfTable.HeaderRows = 1; // repeat header table

        pdfTable.WidthPercentage = 100;

        float[] widths = new float[] { 1f, 1f, 1f, 1f,1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f };
        pdfTable.SetWidths(widths);
        
        PdfPCell cell = new PdfPCell();
        PdfPCell cellRow = new PdfPCell();
                
        //creating table headers
        for (int i = 0; i < cols; i++)
        {
            cell = new PdfPCell();
            cell = new PdfPCell(new Phrase(dataTable.Columns[i].ColumnName, new Font(Font.HELVETICA, 9, Font.HELVETICA)));
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.BorderWidth = 1;
            pdfTable.AddCell(cell);
        }

        //creating table data (actual result)
        for (int k = 0; k < rows; k++)
        {
            for (int j = 0; j < cols; j++) 
            {
                cellRow = new PdfPCell();
                if (dataTable.Rows[k][(this.DropDownList_GroupBy.SelectedValue.Equals("UserIDAffected") ? 5 : 4)].ToString().Equals("")) // Group header
                {
                    cellRow = new PdfPCell(new Phrase("Group by " + this.DropDownList_GroupBy.SelectedItem.Text + ": " + dataTable.Rows[k][(this.DropDownList_GroupBy.SelectedValue.Equals("UserIDAffected") ? 4 : 5)].ToString(), new Font(Font.HELVETICA, 9, Font.BOLD)));
                    cellRow.Colspan = 13;
                    cellRow.HorizontalAlignment = Element.ALIGN_LEFT;
                    cellRow.BorderWidth = 1;
                    pdfTable.AddCell(cellRow);
                    break;
                }
                else // Group details
                {
                    cellRow = new PdfPCell(new Phrase(dataTable.Rows[k][j].ToString(), new Font(Font.HELVETICA, 9, Font.NORMAL)));

                    switch (j)
                    {
                        case 0:  // Instance
                        case 5:  // Employee ID
                        case 6:  // Entity Code
                        case 7:  // Company ID
                        case 10: // Action
                            cellRow.HorizontalAlignment = Element.ALIGN_CENTER;
                            break;
                    }
                    cellRow.BorderWidth = 1;
                    pdfTable.AddCell(cellRow);
                }
            }
        }
        
        pdfDoc.AddTitle("This is the tittle of Pi");

        string entity = DropDownList_ByEntity.SelectedItem.Text;// "Singapore";
        string company = DropDownList_ByCompany.SelectedItem.Text;// "Covidien Private Limited";
        string dateRange = TextBox_SubmittedDateFrom.Text + " - "+ TextBox_SubmittedDateTo.Text;
        string lsSpace = string.Empty;
        lsSpace = lsSpace.PadRight(50 - entity.Length, ' ');

        iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(Server.MapPath("img") + "\\CovidienLogo-ezyclaim.jpg"); //.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg);;
        logo.ScalePercent(60);
        pdfDoc.Add(logo);
        
        Font textFont = FontFactory.GetFont(FontFactory.HELVETICA, 8);
        Font logFont = FontFactory.GetFont(FontFactory.HELVETICA, 16, Font.BOLD);

        Paragraph pTitle = new Paragraph("Log Changes", logFont);
        pTitle.Alignment = 1;
        pdfDoc.Add(pTitle);

        string printDate = SwissArmy.DateConvert(DateTime.Now, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedDateFormat, "/", true);
        Paragraph pPrintDate = new Paragraph("Printed Date: " + printDate, textFont);
        pPrintDate.Alignment = 2;
        pdfDoc.Add(pPrintDate);
        
        textFont = FontFactory.GetFont(FontFactory.HELVETICA, 11);
        pdfDoc.Add(new Chunk("Entity: " + entity + lsSpace + "   Company: " + company + "\n", textFont));
        pdfDoc.Add(new Chunk("Date Range: " + dateRange + "\n", textFont));

        pdfDoc.Add(pdfTable);
        pdfDoc.Close();

        //////////////////////////////////////////////////////////////////// set Page Number /////////////////////////////////////////////////////////////
        // read the initial pdf document
        PdfReader reader = new PdfReader(mStream.ToArray());
        int totalPages = reader.NumberOfPages;
        // add page numbers
        Document copyDoc = new Document();

        System.IO.MemoryStream copymStream = new System.IO.MemoryStream();
        PdfCopy copyPdf = new PdfCopy(copyDoc, copymStream);
        copyPdf.SetPageSize(PageSize.A4.Rotate());
        copyDoc.Open();

        PdfImportedPage copiedPage = null;
        iTextSharp.text.pdf.PdfCopy.PageStamp stamper = null;
        for (int i = 0; i < totalPages; i++)
        {
            // get the page and create a stamper for that page
            copiedPage = copyPdf.GetImportedPage(reader, (i + 1));
            stamper = copyPdf.CreatePageStamp(copiedPage);
            // add a page number to the page
            ColumnText.ShowTextAligned(stamper.GetUnderContent(), Element.ALIGN_CENTER, new Phrase("Page " +(i + 1) + " of " + totalPages + " Pages", textFont), 410f, 10, 0);
            stamper.AlterContents();
            // add the altered page to the new document
            copyPdf.AddPage(copiedPage);
        }

        copyDoc.Close();
        reader.Close();
        // flush and clear the document from memory
        copymStream.Flush();
        copymStream.Close();
        mStream.Flush();
        mStream.Close();
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + pdfFileName);
        Response.Clear();
        Response.BinaryWrite(copymStream.ToArray());
        Response.End();
        return true;
    }

    protected void DropDownList_ByEntity_SelectedIndexChanged(object sender, EventArgs e)
    {
        using (CompanyManager CurCompanyManager = new CompanyManager(this.CurrentPrivateSession))
        {
            GonzalesCompanies ResultList = CurCompanyManager.GetCompanyByEntityID(this.DropDownList_ByEntity.SelectedValue);

            if (ResultList != null)
            {
                this.DropDownList_ByCompany.Items.Clear();
                this.DropDownList_ByCompany.Items.Add(new System.Web.UI.WebControls.ListItem("", ""));

                for (int x = 0; x < ResultList.Count; x++)
                {
                    this.DropDownList_ByCompany.Items.Add(new System.Web.UI.WebControls.ListItem(ResultList[x].CompanyName, ResultList[x].InternalID));
                }
            }
            else
            {
                this.CurLogManager.LogError("[GonzalesLogChangeAuthorizer.DropDownList_ByEntity_SelectedIndexChanged] : Failed on CurCompanyManager.GetCompanyByEntityID('" + this.DropDownList_ByEntity.SelectedValue + "') : " + CurCompanyManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
            }
        }

        #region Filter the company by Finance Admin
        if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsFinanceAdmin)
        {
            using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
            {
                GonzalesCompanies ResultCompanies = CurUserManager.GetCompanyByFinanceAdmin(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID);
                if (ResultCompanies != null)
                {
                    int x = 1;

                    while (x < this.DropDownList_ByCompany.Items.Count)
                    {
                        bool Matched = false;

                        for (int y = 0; y < ResultCompanies.Count; y++)
                        {
                            if (ResultCompanies[y].InternalID.CompareTo(this.DropDownList_ByCompany.Items[x].Value) == 0)
                            {
                                Matched = true;
                                break;
                            }
                        }

                        if (!Matched)
                        {
                            this.DropDownList_ByCompany.Items.RemoveAt(x);
                        }
                        else
                        {
                            x++;
                        }
                    }
                }
            }
        }
        #endregion
    }

    #region OnRowCreated
    protected void OnRowCreated(object sender, GridViewRowEventArgs e)
    {

    }
    #endregion

    #endregion

    #region Customized Methods

    #region SessionCheck
    public void SessionCheck()
    {

        if (Session[GonzalesCommonNamingConvention.CurrentPrivateSession] != null)
        {
            this.CurrentPrivateSession = (PrivateLoginSession)Session[GonzalesCommonNamingConvention.CurrentPrivateSession];
            this.CurLogManager = new LogManager(this.CurrentPrivateSession);    // activate Log Manager
        }
        else
        {
            Response.Redirect(GonzalesErrorPageRedirect.SessionError);
        }

    }
    #endregion

    #region PageComponentSetup
    protected void PageComponentSetup()
    {
        this.img_calendarFrom.Attributes["onClick"] = "popUpCalendar(this, document.getElementById('TextBox_SubmittedDateFrom') , '" + SwissArmy.DateFormatForDisplay(this.CurrentPrivateSession.DateFormatInUse, "/") + "');"; ;
        this.img_calendarTo.Attributes["onClick"] = "popUpCalendar(this, document.getElementById('TextBox_SubmittedDateTo') , '" + SwissArmy.DateFormatForDisplay(this.CurrentPrivateSession.DateFormatInUse, "/") + "');"; ;

        // setup entity
        if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsPowerAdmin || this.CurrentPrivateSession.CurrentLoggedOnUser.IsITAdmin)
        {
            #region Power Admin/ IT Admin
            using (EntityManager CurEntityManager = new EntityManager(this.CurrentPrivateSession))
            {
                MasterBaseCollection ResultList = CurEntityManager.GetAllEntity();
                if (ResultList != null)
                {
                    this.DropDownList_ByEntity.Items.Add(new System.Web.UI.WebControls.ListItem("", ""));
                    for (int x = 0; x < ResultList.Count; x++)
                    {
                        this.DropDownList_ByEntity.Items.Add(new System.Web.UI.WebControls.ListItem(ResultList[x].DisplayName, ResultList[x].InternalID));
                    }
                }
                else
                {
                    // display error
                    this.CurLogManager.LogError("[GonzalesLogChangeAuthorizer.PageComponentSetup] : Failed on CurEntityManager.GetAllEntity() : " + CurEntityManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);

                }
            }
            #endregion
        }
        else
        {
            #region Finance Admin

            using (UserManager CurManager = new UserManager(this.CurrentPrivateSession))
            {
                MasterBaseCollection ResultList = CurManager.GetEntityByFinanceAdmin(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID);
                if (ResultList != null)
                {
                    for (int x = 0; x < ResultList.Count; x++)
                    {
                        this.DropDownList_ByEntity.Items.Add(new System.Web.UI.WebControls.ListItem(ResultList[x].DisplayName, ResultList[x].InternalID));
                    }
                }
                else
                {
                    // display error
                    this.CurLogManager.LogError("[GonzalesLogChangeAuthorizer.PageComponentSetup] : Failed on CurEntityManager.GetAllEntity() : " + CurManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                }
            }

            #endregion
        }

        this.DropDownList_ByEntity_SelectedIndexChanged(null, null);
    }
    #endregion

    #region SwitchLanguage
    protected void SwitchLanguage()
    {
        try
        {
            using (MultiLingualFactory CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
            {
                this.Label_Company.Text = CurLanguageFactory.DisplayValue("Company");
                this.Label_DateRange.Text = CurLanguageFactory.DisplayValue("DateRange");
                this.Label_Entity.Text = CurLanguageFactory.DisplayValue("Entity");
                this.Label_Information.Text = CurLanguageFactory.DisplayValue("Information");
                this.Label_PageTitle.Text = CurLanguageFactory.DisplayValue("PageTitle");
                this.Button_CSV.Text = CurLanguageFactory.DisplayValue("CSV");
                this.Button_Submit.Text = CurLanguageFactory.DisplayValue("Submit");
                this.Download = CurLanguageFactory.DisplayValue("Download");
                this.UnexpectedError = CurLanguageFactory.DisplayValue("UnexpectedMessage");
                this.DateRangeMessage = CurLanguageFactory.DisplayValue("DateRangeMessage");
                this.ProperDateMessage = CurLanguageFactory.DisplayValue("ProperDateMessage");
                this.Label_Sorting.Text = CurLanguageFactory.DisplayValue("Sorting");
                this.Label_Grouping.Text = CurLanguageFactory.DisplayValue("Grouping");

                //this.GridViewHeader = new ArrayList();
                //this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("Instance"));
                //this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("DateTime"));
                //this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("LogBy"));
                //this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("EmployeeID"));
                //this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("EntityCompany"));
                //this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("Module"));
                //this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("ChangeField"));
                //this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("Action"));
                //this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("PreviousValue"));
                //this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("NewValue"));

                // group by
                this.DropDownList_GroupBy.Items.Add(new System.Web.UI.WebControls.ListItem(CurLanguageFactory.DisplayValue("UserIDAffected"), "UserIDAffected"));
                this.DropDownList_GroupBy.Items.Add(new System.Web.UI.WebControls.ListItem(CurLanguageFactory.DisplayValue("EmployeeID"), "EmployeeID"));

                // sort by
                this.DropDownList_SortBy.Items.Add(new System.Web.UI.WebControls.ListItem("", ""));
                this.DropDownList_SortBy.Items.Add(new System.Web.UI.WebControls.ListItem(CurLanguageFactory.DisplayValue("Instance"), "Instance"));
                this.DropDownList_SortBy.Items.Add(new System.Web.UI.WebControls.ListItem(CurLanguageFactory.DisplayValue("DateTime"), "DateTime"));
                this.DropDownList_SortBy.Items.Add(new System.Web.UI.WebControls.ListItem(CurLanguageFactory.DisplayValue("LogBy"), "LoggedBy"));
                this.DropDownList_SortBy.Items.Add(new System.Web.UI.WebControls.ListItem(CurLanguageFactory.DisplayValue("LogByRole"), "LoggedByRole"));
                //this.DropDownList_SortBy.Items.Add(new System.Web.UI.WebControls.ListItem(CurLanguageFactory.DisplayValue("UserIDAffected"), "UserIDAffected"));
                //this.DropDownList_SortBy.Items.Add(new System.Web.UI.WebControls.ListItem(CurLanguageFactory.DisplayValue("EmployeeID"), "EmployeeID"));
                this.DropDownList_SortBy.Items.Add(new System.Web.UI.WebControls.ListItem(CurLanguageFactory.DisplayValue("EntityCode"), "EntityCode"));
                this.DropDownList_SortBy.Items.Add(new System.Web.UI.WebControls.ListItem(CurLanguageFactory.DisplayValue("CompanyID"), "CompanyID"));
                this.DropDownList_SortBy.Items.Add(new System.Web.UI.WebControls.ListItem(CurLanguageFactory.DisplayValue("Module"), "Module"));
                this.DropDownList_SortBy.Items.Add(new System.Web.UI.WebControls.ListItem(CurLanguageFactory.DisplayValue("ChangeFiled"), "ChangeField"));
                this.DropDownList_SortBy.Items.Add(new System.Web.UI.WebControls.ListItem(CurLanguageFactory.DisplayValue("Action"), "Action"));
                this.DropDownList_SortBy.Items.Add(new System.Web.UI.WebControls.ListItem(CurLanguageFactory.DisplayValue("PreviousValue"), "PreviousValue"));
                this.DropDownList_SortBy.Items.Add(new System.Web.UI.WebControls.ListItem(CurLanguageFactory.DisplayValue("NewValue"), "NewValue"));

                this.DropDownList_SortOrder.Items.Add(new System.Web.UI.WebControls.ListItem(CurLanguageFactory.DisplayValue("ASC"), "ASC"));
                this.DropDownList_SortOrder.Items.Add(new System.Web.UI.WebControls.ListItem(CurLanguageFactory.DisplayValue("DESC"), "DESC"));
            }
        }
        catch (Exception ex)
        {
            this.CurLogManager.LogError("[GonzalesLogChangeAuthorizer.SwitchLanguage.EX] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }

    }
    #endregion

    #region ShowErrorMessage
    protected void ShowErrorMessage(string ErrorMessage)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = ErrorMessage;
        this.Table_MessageBox.Rows[0].Cells[0].CssClass = "ErrorBox";
    }
    #endregion

    #region ShowMessage
    protected void ShowMessage(string Message)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = Message;
        this.Table_MessageBox.Rows[0].Cells[0].CssClass = "MessageBox";
    }
    #endregion

    #endregion

    #region Data Operation

    #region LoadData
    protected void LoadData()
    {
        using (ReportsGenerator CurReportGenerator = new ReportsGenerator(this.CurrentPrivateSession))
        {
            this.ResultTable = CurReportGenerator.GetLogChangeByModule(this.DropDownList_ByEntity.SelectedValue, this.DropDownList_ByCompany.SelectedValue, SwissArmy.DateConvert(this.TextBox_SubmittedDateFrom.Text, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedDateFormat), SwissArmy.DateConvert(this.TextBox_SubmittedDateTo.Text, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedDateFormat));

            if (ResultTable != null)
            {
                this.ResultView = new DataView(this.ResultTable);

                if (this.ResultView.Count > 0)
                {
                    this.ResultView.Sort = BuildSorting();

                    int rc = this.ResultView.Count - 1;
                    DataRowView drView = null;
                    string lsOldValue = this.ResultView[rc][this.DropDownList_GroupBy.SelectedValue].ToString();
                    drView = this.ResultView.AddNew();

                    drView[this.DropDownList_GroupBy.SelectedValue] = lsOldValue;
                    if (this.DropDownList_SortOrder.SelectedValue.Equals("DESC"))
                        drView[this.DropDownList_SortBy.SelectedValue] = "Z";
                    drView.EndEdit();

                    string lsNewValue = string.Empty;

                    for (int i = rc - 1; i > -1; i--)
                    {
                        lsNewValue = this.ResultView[i][this.DropDownList_GroupBy.SelectedValue].ToString();
                        if (lsNewValue.CompareTo(lsOldValue) != 0)
                        {
                            drView = this.ResultView.AddNew();
                            drView[this.DropDownList_GroupBy.SelectedValue] = lsNewValue;
                            if (this.DropDownList_SortOrder.SelectedValue.Equals("DESC"))
                                drView[this.DropDownList_SortBy.SelectedValue] = "Z";
                            lsOldValue = lsNewValue;
                            drView.EndEdit();
                        }
                    }
                }
                
            }
            else //if (this.ResultTable == null)
            {
                string LogID = SwissArmy.UniqueID();
                this.CurLogManager.LogError(LogID, "[GonzalesLogChangeAuthorizer.LoadData] : Failed at CurReportGenerator.GetClaimantReportsByCompany('" + this.DropDownList_ByCompany.SelectedValue + "') : " + CurReportGenerator.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                this.ShowErrorMessage(this.UnexpectedError + LogID);
            }
        }
    }

    #endregion

    protected string BuildSorting()
    { 
        string lsSorting = string.Empty;

        if (this.DropDownList_SortBy.SelectedValue.CompareTo("") != 0)
        {
            lsSorting = this.DropDownList_GroupBy.SelectedValue + ", " + this.DropDownList_SortBy.SelectedValue + /*", " + (this.DropDownList_GroupBy.SelectedValue.Equals("UserIDAffected") ? "EmployeeID" : "UserIDAffected") +*/ " " + this.DropDownList_SortOrder.SelectedValue;
        }
        else
        {
            lsSorting = this.DropDownList_GroupBy.SelectedValue + ", " + (this.DropDownList_GroupBy.SelectedValue.Equals("UserIDAffected") ? "EmployeeID" : "UserIDAffected");
        }

        return lsSorting;
    }

    #region BindData
    private void BindData(DataView result)
    {
        this.GridViewResult.DataSource = result;
        this.GridViewResult.DataBind();
    }

    private void BindData(DataView result, int pageindex)
    {
        this.GridViewResult.PageIndex = pageindex;
        this.GridViewResult.DataSource = result;
        this.GridViewResult.DataBind();
    }
    #endregion

    #endregion

    #region GridViewResult_RowDataBound
    protected void GridViewResult_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int col = (this.DropDownList_GroupBy.SelectedValue.Equals("UserIDAffected") ? 5 : 4);
            if (e.Row.Cells[col].Text.Equals("&nbsp;"))
            {
                e.Row.Cells[1].Visible = e.Row.Cells[2].Visible = e.Row.Cells[3].Visible = e.Row.Cells[4].Visible = 
                e.Row.Cells[5].Visible = e.Row.Cells[6].Visible = e.Row.Cells[7].Visible = e.Row.Cells[8].Visible = 
                e.Row.Cells[9].Visible = e.Row.Cells[10].Visible = e.Row.Cells[11].Visible = e.Row.Cells[12].Visible = false;
                e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Left;
                e.Row.Cells[0].Text = "Group by " + this.DropDownList_GroupBy.SelectedItem.Text + ": " + e.Row.Cells[(this.DropDownList_GroupBy.SelectedValue.Equals("UserIDAffected") ? 4 : 5)].Text;
                e.Row.Cells[0].ColumnSpan = 13;
                e.Row.Font.Bold = true;
                e.Row.CssClass = "MessageBox";
            }
        }
    }
    #endregion
}
